#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
应用主模块
"""

import asyncio
import json
from pathlib import Path
from typing import Dict, List

from core.agents.factory import agent_manager
from core.eval import run_evaluation_interactive
from core.llm.factory import ModelType
from core.utils.log import mylogger


class App:
    """应用主类，整合新的Agent架构"""

    def __init__(self):
        self.input_file_path = Path(__file__).parent.parent / "data" / "input.json"
        self.model_types = [ModelType.DOUBAO_FLASH, ModelType.DOUBAO_PRO]
        self.model_names = {
            ModelType.DOUBAO_FLASH: "doubaoFlash",
            ModelType.DOUBAO_PRO: "doubaoPro",
        }

    def _load_input_data(self) -> List[Dict]:
        """从input.json加载输入数据"""
        try:
            with open(self.input_file_path, "r", encoding="utf-8") as f:
                input_data = json.load(f)
            mylogger.info(f"成功加载输入文件: {self.input_file_path}")
            return input_data if isinstance(input_data, list) else [input_data]
        except (FileNotFoundError, json.JSONDecodeError) as e:
            mylogger.error(f"无法读取输入文件 {self.input_file_path}: {e}")
            raise

    def _save_result_data(self, result_data: List[Dict], model_type: ModelType):
        """保存结果数据到特定模型的output.json"""
        try:
            model_name = self.model_names[model_type]
            output_path = (
                Path(__file__).parent.parent / "data" / f"{model_name}_output.json"
            )

            output_path.parent.mkdir(parents=True, exist_ok=True)

            with open(output_path, "w", encoding="utf-8") as f:
                json.dump(result_data, f, ensure_ascii=False, indent=4)
            mylogger.info(f"成功保存结果到: {output_path}")
        except Exception as e:
            mylogger.error(f"保存结果文件失败: {e}")
            raise

    def _save_json_results(self, all_results: Dict[ModelType, List[Dict]]):
        """将所有模型的结果保存到JSON文件"""
        try:
            json_path = Path(__file__).parent.parent / "data" / "result.json"
            json_path.parent.mkdir(parents=True, exist_ok=True)

            json_data = []
            inputs = [
                item["input"] for item in all_results[list(all_results.keys())[0]]
            ]

            for i, input_text in enumerate(inputs):
                json_obj = {"id": i + 1, "input": input_text if input_text else ""}

                for model_type in all_results:
                    model_name = self.model_names[model_type]
                    response = all_results[model_type][i]["response"]
                    json_obj[f"{model_name}_output"] = (
                        str(response) if response is not None else ""
                    )

                json_data.append(json_obj)

            with open(json_path, "w", encoding="utf-8") as f:
                json.dump(json_data, f, ensure_ascii=False, indent=2)

            mylogger.info(f"成功保存JSON结果到: {json_path}")
        except Exception as e:
            mylogger.error(f"保存JSON结果文件失败: {e}")
            raise

    async def proces_mutiltrun(self, npc_name: str):
        input_data_list = self._load_input_data()
        all_results = {}

        for model_type in self.model_types:
            dialogue_agent = agent_manager.get_dialogue_agent(npc_name, model_type)
            memory_agent = agent_manager.get_memory_agent(npc_name, model_type)
            model_name = self.model_names[model_type]
            mylogger.info(f"使用模型 {model_name} 处理对话")

            result_data = []

            for input_item in input_data_list:
                user_input = input_item.get("input", "")
                mylogger.info(f"处理输入: {user_input}")

                # 使用dialogue agent生成响应
                full_response = await dialogue_agent.process(input_item)
                print(f"NPC {npc_name} ({model_name}) 回复: {full_response}")
                print("\n")

                # 使用memory agent添加记忆
                await memory_agent.process(
                    {
                        "operation": "add_short_term",
                        "content": f"玩家: {user_input}",
                        "type": "Conversation",
                    }
                )
                await memory_agent.process(
                    {
                        "operation": "add_short_term",
                        "content": f"{npc_name} ({model_name}): {full_response}",
                        "type": "Conversation",
                    }
                )

                # 获取记忆统计
                memory_stats_result = await memory_agent.process(
                    {"operation": "get_stats"}
                )
                memory_stats = memory_stats_result["stats"]
                mylogger.debug(
                    f"记忆状态 ({model_name}): 短期记忆 {memory_stats['short_term_count']}/{memory_stats['short_term_limit']}, 长期记忆 {memory_stats['long_term_count']}/{memory_stats['long_term_limit']}"
                )

                # 获取记忆上下文
                memory_context_result = await memory_agent.process(
                    {"operation": "get_context"}
                )
                memory_context = memory_context_result["context"]
                mylogger.debug(f"当前记忆上下文 ({model_name}): {memory_context}")

                result_data.append({"input": user_input, "response": full_response})
                mylogger.info(
                    f"对话轮次完成 ({model_name})，玩家输入: {user_input}, NPC回复: {full_response}"
                )

            self._save_result_data(result_data, model_type)
            all_results[model_type] = result_data

        self._save_json_results(all_results)
        return all_results

    async def run_evaluation(self, npc_name: str):
        """运行评测，使用新的Agent架构"""
        mylogger.info(f"开始为角色 {npc_name} 运行评测")
        await run_evaluation_interactive(npc_name)
        mylogger.info(f"角色 {npc_name} 评测完成")


async def main():
    """主函数"""
    app = App()
    npc_name = "赵凤儿"

    await app.proces_mutiltrun(npc_name=npc_name)
    mylogger.info("多轮对话处理完成")


if __name__ == "__main__":
    asyncio.run(main())
